<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;

class LoginController extends Controller
{
    public function login(Request $i) {
        $password = $i->input('password');
        $username = $i->input('username');
        $password = sha1($password);
        $user     = User::where('name', $username)->where('password', $password)->first();
        $token    = sha1(time().rand(1000, 9999));
        if ($user) {
            $user->remember_token = $token;
            $user->save();
            return self::success(['token' => $token]);
        } else {
            return self::fail("登录失败");
        }
    }

    public function info(Request $i) {
        $token = $i->input('token');
        $user = User::where('remember_token', $token)->first();
        if ($user) {
            $avatar = url('images/icon/manager.png');
            return self::success(['name'=>$user->name, 'avatar' => $avatar, 'roles'=>['admin'], 'introduction'=>'介绍']);
        }
    }

    public function logout(Request $i) {
        $token = $i->header('X-Token');
        $user = User::where('remember_token', $token)->first();
        if ($user) {
            $user->remember_token = '';
            $user->save();
        }
        return self::success();
    }
}
